﻿using Common.Communal;
using ERP.Domain.Products;
using MediatR;
using Product.API.Read.Applications.Commands.ProductProcess;
using Product.API.Read.DTOS;
using SqlSugar;

namespace Product.API.Read.Applications.CommandHandlers.ProductProcess
{
    /// <summary>
    /// 关联产品显示命令
    /// </summary>
    public class ProductProcessShowCommandHandler : IRequestHandler<ProductProcessShowCommand, ApiResult<List<ProductProcessShowDTO>>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public ProductProcessShowCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">处理</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<List<ProductProcessShowDTO>>> Handle(ProductProcessShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ProductProcessShowDTO>> result = new ApiResult<List<ProductProcessShowDTO>>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();


            var data = db.Queryable<ERP.Domain.Products.BomInfo>()
                .InnerJoin<ERP.Domain.Products.ProductProcess>((a, b) => a.ProductNumber == b.ProductNumber)
                .InnerJoin<ERP.Domain.Products.ProcessRoute>((a, b, c) => b.ProcessRouteNumber == c.ProcessRouteNumber && c.ProcessRouteNumber == request.processRouteNumber)
                .Where(a => a.IsDelete == false)
                .Select((a, b, c) => new ProductProcessShowDTO
                {
                    BomNumber = a.BomNumber,
                    ProductName = a.ProductName,
                    ProductNumber = a.ProductNumber,
                    SpecificationModel = a.SpecificationModel,
                    Unit = a.Unit,
                    BomVersion = a.BomVersion
                }).ToList();

            result.Data = data;

            return Task.FromResult(result);
        }
    }
}
